package com.chookss.home.studyPlan;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.StudyPlanEntiry;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;

@SuppressLint("ValidFragment")
public class StudyPlanFragment extends ImmersionFragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    private MyStudyPlanAdapter adapter;
    private List<StudyPlanEntiry> list = new ArrayList<>();
    private int currentPage = 1;
    private String planStatus = "";
    private boolean isEnd = false;//是否到底

    public StudyPlanFragment(String planStatus) {
        this.planStatus = planStatus;
    }

    public StudyPlanFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.common_srlview_center_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }
    private void init() {
        tvNone.setText("没有学习计划");
        llBg.setBackgroundColor(getResources().getColor(R.color.main_bg));
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new MyStudyPlanAdapter(R.layout.item_study, mContext, list);
        rv.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
    }

    @Override
    public void onLazyAfterView() {
        super.onLazyAfterView();
        KLog.i("onLazyAfterView");
    }

    @Override
    public void onVisible() {
        super.onVisible();
        srlView.autoRefresh();
        KLog.i("onVisible");
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        map.put("planStatus", planStatus);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<StudyPlanEntiry>>>() {
        }.getType(), null, Urls.getStudyPlan, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<StudyPlanEntiry>>() {
            @Override
            public void onSuccess(List<StudyPlanEntiry> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (srlView == null || llNone == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyDataSetChanged();
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    @Override
    public void initImmersionBar() {

    }

    class MyStudyPlanAdapter extends BaseQuickAdapter<StudyPlanEntiry, BaseViewHolderEx> {
        private Context context;

        public MyStudyPlanAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<StudyPlanEntiry> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, StudyPlanEntiry item) {

            TextView tvStudyTitle = helper.getView(R.id.tvStudyTitle);
            TextView tvStudyType = helper.getView(R.id.tvStudyType);
            TextView tvStudyTime = helper.getView(R.id.tvStudyTime);
            TextView tvStudyCycle = helper.getView(R.id.tvStudyCycle);
            TextView tvStudyPeople = helper.getView(R.id.tvStudyPeople);
            TextView tvStudyCompletee = helper.getView(R.id.tvStudyCompletee);
            ProgressBar tvStudyProgressBar = helper.getView(R.id.tvStudyProgressBar);
            TextView tvStudyCompleteePercent = helper.getView(R.id.tvStudyCompleteePercent);
            tvStudyTitle.setText(item.getPlanTitle());
            tvStudyTime.setText("时间：" + Utils.getNormalYMDTime(item.getEff_time()) + "-" + Utils.getNormalYMDTime(item.getInvalid_time()));
            //5 cycle 学习任务
            if ("3".equals(item.getCycle())) {
                tvStudyCycle.setText("周期：每月");
                tvStudyCompletee.setText("当月完成：" + Utils.changeNumber(item.getCompleteNum()) + "/" + Utils.changeNumber(item.getTargetNum()));
            } else if ("5".equals(item.getCycle())) {
                tvStudyCycle.setText("周期：单次");
                tvStudyCompletee.setText("完成：" + Utils.changeNumber(item.getCompleteNum()) + "/" + Utils.changeNumber(item.getTargetNum()));
            } else {
                tvStudyCycle.setText("周期：每天");
                tvStudyCompletee.setText("今日完成：" + Utils.changeNumber(item.getCompleteNum()) + "/" + Utils.changeNumber(item.getTargetNum()));
            }
            if ("1".equals(item.getPlanStatus())) {
                //未开始
                tvStudyType.setText("未开始");
                tvStudyType.setBackgroundResource(R.drawable.shape_eeeeee_3);
                tvStudyType.setTextColor(Color.parseColor("#999999"));
                tvStudyCompletee.setVisibility(View.INVISIBLE);
            } else if ("2".equals(item.getPlanStatus())) {
                //进行中
                if (Utils.changeNumber(item.getCompleteNum()) >= Utils.changeNumber(item.getTargetNum())) {
                    tvStudyType.setText("已完成");
                    tvStudyType.setTextColor(Color.parseColor("#00C993"));
                    tvStudyType.setBackgroundResource(R.drawable.shape_00c993_3);
                } else {
                    tvStudyType.setText("进行中");
                    tvStudyType.setBackgroundResource(R.drawable.shape_11b3ff_3);
                    tvStudyType.setTextColor(Color.parseColor("#11B3FF"));
                }
                tvStudyCompletee.setVisibility(View.VISIBLE);
            } else if ("3".equals(item.getPlanStatus())) {
                //结束
                if (Utils.changeNumber(item.getCompleteNum()) >= Utils.changeNumber(item.getTargetNum())) {
                    tvStudyType.setText("已完成");
                    tvStudyType.setTextColor(Color.parseColor("#00C993"));
                    tvStudyType.setBackgroundResource(R.drawable.shape_00c993_3);
                } else {
                    tvStudyType.setText("未完成");
                    tvStudyType.setTextColor(Color.parseColor("#FFAC1C"));
                    tvStudyType.setBackgroundResource(R.drawable.shape_ffac1c_3);
                }
                tvStudyCompletee.setVisibility(View.VISIBLE);
            }
            tvStudyPeople.setText("发布人：" + item.getEmployeeName());
            tvStudyCompleteePercent.setText("累计完成：" + Utils.changeNumber(item.getTotalCompletePercen()) + "%");
            tvStudyProgressBar.setProgress(Utils.changeNumber(item.getTotalCompletePercen()));
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = null;
                    if ("5".equals(item.getCycle())) {
                        intent = new Intent(mContext, StudyPlanTaskDetailActivity.class);
                    } else {
                        intent = new Intent(mContext, StudyPlanDetailActivity.class);
                    }
                    intent.putExtra("planCode", item.getPlanCode());
                    intent.putExtra("cycle", item.getCycle());
                    intent.putExtra("effTime", item.getEff_time());
                    intent.putExtra("invalidTime", item.getInvalid_time());
                    intent.putExtra("planStatus", item.getPlanStatus());
                    mContext.startActivity(intent);
                }
            });
        }
    }


    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
